#ifndef _COMM_HPP_
#define _COMM_HPP_

#pragma once

#define PATHNAME "."
#define PROJ_ID 0x666
#define MAX_SIZE 4096 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

using namespace std;

key_t getKey()
{
    key_t key = ftok(PATHNAME, PROJ_ID);
    if (key < 0)
    {
        cerr << "getKey: " << strerror(errno) << endl;
        exit(1);//获取key失败 强制退出程序
    }
    return key;
}

int getShmId(key_t key, int flag)
{
    int id = shmget(key, MAX_SIZE, flag);
    if (id < 0)
    {
        cerr << "getShmId: " << strerror(errno) << endl;
        exit(2);//创建共享内存失败
    }
    return id;
}

int createShm(key_t key)//server端创建共享内存
{
    return getShmId(key, IPC_CREAT | IPC_EXCL | 0600);//不存在创建 存在报错
}

int getShm(key_t key)//client端获取共享内存
{
    return getShmId(key, IPC_CREAT);//不存在创建 存在获取
}

void* attachShm(int id)//建立共享内存与进程的联系
{
    void* memory = shmat(id, nullptr, 0);//64位系统 指针8字节
    if ((long long)memory == -1)
    {
        cerr << "attachShm: " << strerror(errno) << endl;
        exit(3);
    }
    return memory;
}

void detachShm(void* start)
{
    if (shmdt(start) == -1)
    {
        cerr << "detachShm: " << strerror(errno) << endl;
        exit(4); 
    }
}

void delShm(int id)
{
    if (shmctl(id, IPC_RMID, nullptr) == -1)
    {
        cerr << "delShm: " << strerror(errno) << endl;
        exit(5);
    }
}

#endif